﻿using System;
using System.Linq;
using Microsoft.Web.Administration;
using NAnt.Core;
using NAnt.Core.Attributes;

namespace ECM7.NantContrib.Tasks.IIS7
{
	public abstract class BaseIisWebsiteObjectTask : BaseTask
	{
		[TaskAttribute("websiteName", Required = true), StringValidator(AllowEmpty = false)]
		public string WebsiteName { get; set; }

		[TaskAttribute("virtualPath", Required = true), StringValidator(AllowEmpty = false)]
		public string VirtualPath { get; set; }

		[TaskAttribute("fileSystemPath", Required = true), StringValidator(AllowEmpty = true)]
		public string FileSystemPath { get; set; }

		[TaskAttribute("server", Required = false), StringValidator(AllowEmpty = false)]
		public string Server { get; set; }

		[TaskAttribute("errorIfAlreadyExists", Required = false), BooleanValidator]
		public bool ErrorIfAlreadyExists { get; set; }

		protected override void ExecuteTask()
		{
			try
			{
				if (string.IsNullOrEmpty(WebsiteName)) { throw new Exception("Parameter [WebsiteName] can't be null or empty"); }
				if (string.IsNullOrEmpty(VirtualPath)) { throw new Exception("Parameter [VirtualPath] can't be null or empty"); }
				if (!VirtualPath.StartsWith("/")) { throw new Exception("Parameter [VirtualPath] should start with \"/\""); }

				if (string.IsNullOrEmpty(FileSystemPath)) { throw new Exception("Parameter [FileSystemPath] can't be null or empty"); }

				string server = string.IsNullOrWhiteSpace(Server) ? "localhost" : Server.Trim();

				using (ServerManager serverMgr = ServerManager.OpenRemote(server))
				{
					Site site = serverMgr.Sites[WebsiteName];

					if (site == null)
					{
						throw new Exception(string.Format("Website [{0}] is not exists", WebsiteName));
					}

					ChangeIisConfiguration(site);
					serverMgr.CommitChanges();
				}
			}
			catch (Exception ex)
			{
				LogError("[{0}{1}] not created, because an exception occurred [{2}]", WebsiteName, VirtualPath, ex);
				throw new BuildException("Unable to change iis configuration", ex);
			}
		}

		protected abstract void ChangeIisConfiguration(Site site);
	}
}
